<template>
  <div class="insurance-application-submodule p-4">
    <!-- 页面标题 -->
    <div class="page-header mb-6">
      <h2 class="text-xl font-bold text-gray-800">农业保险投保</h2>
      <p class="text-gray-500 text-sm">请完成以下信息填写，带 <span class="text-red-500">*</span> 为必填项</p>
    </div>

    <!-- 步骤指示器 -->
    <el-steps :active="currentStep" finish-status="success" class="mb-8">
      <el-step title="农户信息" icon="el-icon-user"></el-step>
      <el-step title="投保详情" icon="el-icon-document"></el-step>
      <el-step title="确认提交" icon="el-icon-check"></el-step>
    </el-steps>

    <!-- 步骤内容区域 -->
    <div class="step-content-container bg-white p-6 rounded-lg shadow-sm border border-gray-100">
      <!-- 步骤1：农户信息 -->
      <div v-if="currentStep === 1" class="step-content animate-fadeIn">
        <el-form ref="farmerForm" :model="farmerInfo" :rules="farmerRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="insuredName">
                <el-input v-model="farmerInfo.insuredName" placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="farmerInfo.phone" placeholder="请输入手机号码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="身份证号码" prop="idCard">
                <el-input v-model="farmerInfo.idCard" placeholder="请输入18位身份证号码"></el-input>
                <el-form-item__help>我们将对您的身份信息进行验证</el-form-item__help>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="详细地址" prop="address">
                <el-input v-model="farmerInfo.address" placeholder="请输入详细地址，如：XX省XX市XX县XX村"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开户银行" prop="bankName">
                <el-select v-model="farmerInfo.bankName" placeholder="请选择银行">
                  <el-option label="中国农业银行" value="中国农业银行"></el-option>
                  <el-option label="中国邮政储蓄银行" value="中国邮政储蓄银行"></el-option>
                  <el-option label="中国工商银行" value="中国工商银行"></el-option>
                  <el-option label="中国建设银行" value="中国建设银行"></el-option>
                  <el-option label="中国银行" value="中国银行"></el-option>
                  <el-option label="其他银行" value="其他银行"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行卡号" prop="bankCard">
                <el-input v-model="farmerInfo.bankCard" placeholder="请输入银行卡号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="form-actions mt-6 flex justify-end">
            <el-button type="primary" @click="nextStep" :loading="loading">
              下一步 <i class="el-icon-arrow-right ml-1"></i>
            </el-button>
          </div>
        </el-form>
      </div>

      <!-- 步骤2：投保详情（新增投保业务员下拉框） -->
      <div v-if="currentStep === 2" class="step-content animate-fadeIn">
        <el-form ref="insureForm" :model="insureOrder" :rules="insureRules" label-width="120px">
          <!-- 1. 险种类型选择 -->
          <el-form-item label="险种类型" prop="coverageType">
            <el-select
                v-model="insureOrder.coverageType"
                placeholder="请先选择险种类型"
                @change="handleCoverageTypeChange"
                :disabled="loading"
            >
              <el-option label="种植业" value="1"></el-option>
              <el-option label="养殖业" value="2"></el-option>
              <el-option label="其他农险" value="3"></el-option>
            </el-select>
          </el-form-item>

          <!-- 2. 险种名称选择 -->
          <el-form-item label="险种名称" prop="coverageName" v-if="insureOrder.coverageType">
            <el-select
                v-model="insureOrder.coverageName"
                placeholder="请选择具体险种"
                @change="handleCoverageNameSelect"
                :disabled="loading || !coverageNameList.length"
                clearable
            >
              <el-option
                  v-for="name in coverageNameList"
                  :key="name"
                  :label="name"
                  :value="name"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 3. 投保项目输入框 -->
          <el-form-item
              label="投保项目"
              prop="insuranceSubject"
              v-if="insureOrder.coverageName"
          >
            <el-input
                v-model="insureOrder.insuranceSubject"
                placeholder="请输入具体投保项目（如：小麦、育肥猪、蔬菜大棚）"
                :disabled="loading"
                clearable
            ></el-input>
            <el-form-item__help>根据所选险种填写具体投保对象，如种植业填作物名称，养殖业填养殖品种</el-form-item__help>
          </el-form-item>

          <!-- 4. 新增：投保业务员下拉选择 -->
          <el-form-item
              label="投保业务员"
              prop="insureUser"
              v-if="insureOrder.coverageName && surveyorOptions.length > 0"
          >
            <el-select
                v-model="selectedSurveyor"
                placeholder="请选择投保业务员"
                @change="handleSurveyorChange"
                :disabled="loading"
                clearable
            >
              <el-option
                  v-for="surveyor in surveyorOptions"
                  :key="surveyor.id"
                  :label="surveyor.name"
                  :value="surveyor.id"
              ></el-option>
            </el-select>
            <el-form-item__help>请选择为您服务的投保业务员，若无则选择“系统自动分配”</el-form-item__help>
          </el-form-item>

          <!-- 5. 保险期间 -->
          <el-row :gutter="20" v-if="insureOrder.coverageName">
            <el-col :span="12">
              <el-form-item label="保险起期" prop="startDate">
                <el-date-picker
                    v-model="insureOrder.startDate"
                    type="date"
                    placeholder="选择保险起期"
                    :min-date="minStartDate"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    :disabled="loading"
                    @blur="validateLocalDate('startDate')"
                    clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="保险止期" prop="endDate">
                <el-date-picker
                    v-model="insureOrder.endDate"
                    type="date"
                    placeholder="选择保险止期"
                    :min-date="insureOrder.startDate ? new Date(insureOrder.startDate) : ''"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    :disabled="loading || !insureOrder.startDate"
                    @blur="validateLocalDate('endDate')"
                    clearable
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 6. 面积/数量 -->
          <el-form-item
              v-if="insureOrder.coverageName"
              :label="getQuantityLabel()"
              :prop="isCropType ? 'coverageArea' : 'coverageQuantity'"
          >
            <el-input
                v-model.number="currentQuantity"
                placeholder="请输入数量"
                @input="handleQuantityInput"
                type="number"
                :min="isCropType ? 0.1 : 1"
                :step="isCropType ? 0.1 : 1"
                :disabled="loading || !insureOrder.coverageName || !insureOrder.unitInsured || insureOrder.unitInsured === '0.00'"
            ></el-input>
          </el-form-item>

          <!-- 7. 保费计算结果 -->
          <el-card shadow="hover" class="mt-4" :loading="loading" v-if="insureOrder.coverageName">
            <div slot="header" class="font-medium">保费计算结果</div>
            <el-row :gutter="10" class="text-sm">
              <el-col :span="8">
                <p class="text-gray-500">单位保额</p>
                <p class="font-medium">{{ insureOrder.unitInsured || '0.00' }}
                  元/{{ isCropType ? '亩' : getQuantityUnit() }}</p>
              </el-col>
              <el-col :span="8">
                <p class="text-gray-500">总保额</p>
                <p class="font-medium">{{ insureOrder.sumInsured || '0.00' }} 元</p>
              </el-col>
              <el-col :span="8">
                <p class="text-gray-500">总保费(总保额的百分之五)</p>
                <p class="font-medium font-bold text-emerald-700">{{ insureOrder.totalPremium || '0.00' }} 元</p>
              </el-col>
            </el-row>
          </el-card>

          <!-- 步骤按钮 -->
          <div class="form-actions mt-6 flex justify-between" v-if="insureOrder.coverageName">
            <el-button @click="prevStep" :disabled="loading">
              <i class="el-icon-arrow-left mr-1"></i> 上一步
            </el-button>
            <el-button
                type="primary"
                @click="nextStep"
                :disabled="loading || !insureOrder.startDate || !insureOrder.endDate || (!insureOrder.coverageArea && !insureOrder.coverageQuantity) || !insureOrder.sumInsured || insureOrder.sumInsured === '0.00' || !insureOrder.insuranceSubject || !selectedSurveyor"
            >
              下一步 <i class="el-icon-arrow-right ml-1"></i>
            </el-button>
          </div>
        </el-form>
      </div>

      <!-- 步骤3：确认提交（展示选中的投保业务员） -->
      <div v-if="currentStep === 3" class="step-content animate-fadeIn">
        <el-card shadow="hover" class="mb-4">
          <div slot="header" class="font-medium">农户信息</div>
          <el-descriptions column="1" border>
            <el-descriptions-item label="姓名">{{ farmerInfo.insuredName }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ maskIdCard(farmerInfo.idCard) }}</el-descriptions-item>
            <el-descriptions-item label="手机号码">{{ farmerInfo.phone }}</el-descriptions-item>
            <el-descriptions-item label="详细地址">{{ farmerInfo.address }}</el-descriptions-item>
            <el-descriptions-item label="收款账户">{{ farmerInfo.bankName }} ({{
                maskBankCard(farmerInfo.bankCard)
              }})
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-card shadow="hover" class="mb-4">
          <div slot="header" class="font-medium">投保信息</div>
          <el-descriptions column="1" border>
            <el-descriptions-item label="险种类型">{{
                coverageTypeText[insureOrder.coverageType]
              }}
            </el-descriptions-item>
            <el-descriptions-item label="险种名称">{{ insureOrder.coverageName }}</el-descriptions-item>
            <el-descriptions-item label="投保项目">{{ insureOrder.insuranceSubject }}</el-descriptions-item>
            <!-- 展示选中的投保业务员姓名 -->
            <el-descriptions-item label="投保业务员">{{ selectedSurveyorName || '系统自动分配' }}</el-descriptions-item>
            <el-descriptions-item label="保险期间">{{ insureOrder.startDate }} 至 {{
                insureOrder.endDate
              }}
            </el-descriptions-item>
            <el-descriptions-item label="承保数量">
              {{ isCropType ? insureOrder.coverageArea : insureOrder.coverageQuantity }}
              <span v-if="isCropType">亩</span>
              <span v-else>{{ getQuantityUnit() }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="单位保额">{{ insureOrder.unitInsured }}
              元/{{ isCropType ? '亩' : getQuantityUnit() }}
            </el-descriptions-item>
            <el-descriptions-item label="总保额">{{ insureOrder.sumInsured }} 元</el-descriptions-item>
            <el-descriptions-item label="总保费">{{ insureOrder.totalPremium }} 元</el-descriptions-item>
            <el-descriptions-item label="缴费状态">{{ getPayStatusText(insureOrder.payStatus) }}</el-descriptions-item>
            <el-descriptions-item label="保单状态">{{
                getPolicyStatusText(insureOrder.policyStatus)
              }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 费用信息、投保声明、提交按钮 -->
        <el-card shadow="hover" class="mb-4">
          <div slot="header" class="font-medium">费用信息</div>
          <el-descriptions column="1" border>
            <el-descriptions-item label="总保费" label-class-name="text-emerald-700 font-bold">
              {{ insureOrder.totalPremium }} 元
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <el-alert
            title="投保声明"
            type="warning"
            description="本人确认所填写和提供的信息真实有效，已了解并同意保险条款及相关规定，自愿投保本保险产品。"
            show-icon
            class="mb-4"
        ></el-alert>

        <el-form-item>
          <el-checkbox v-model="agreeTerms" :disabled="submitting">
            我已阅读并同意<a href="#" class="text-emerald-600 hover:underline">《保险条款》</a>和<a href="#"
                                                                                                  class="text-emerald-600 hover:underline">《隐私政策》</a>
          </el-checkbox>
        </el-form-item>

        <div class="form-actions mt-6 flex justify-between">
          <el-button @click="prevStep" :disabled="submitting">
            <i class="el-icon-arrow-left mr-1"></i> 上一步
          </el-button>
          <el-button
              type="primary"
              @click="submitAll"
              :loading="submitting"
              :disabled="submitting || !agreeTerms || !insureOrder.coverageName || !insureOrder.insuranceSubject || !selectedSurveyor"
          >
            确认提交
          </el-button>
        </div>
      </div>

      <!-- 提交成功 -->
      <div v-if="submittedSuccessfully" class="step-content text-center animate-fadeIn">
        <el-result
            icon="success"
            title="投保申请提交成功！"
            subTitle="您的保单编号：<span class='font-medium text-emerald-700'>{{ generatedPolicyId }}</span>"
        >
          <template slot="extra">
            <el-card shadow="hover" class="max-w-md mx-auto mb-6 text-left">
              <el-descriptions column="1" :column="12" border>
                <el-descriptions-item label="审核周期" :span="12">我们将在1-3个工作日内完成审核</el-descriptions-item>
                <el-descriptions-item label="通知方式" :span="12">审核结果将通过短信发送至您的手机：{{
                    farmerInfo.phone
                  }}
                </el-descriptions-item>
                <el-descriptions-item label="当前状态" :span="12">
                  缴费状态：{{ getPayStatusText(1) }} | 保单状态：{{ getPolicyStatusText(1) }}
                </el-descriptions-item>
                <el-descriptions-item label="投保业务员" :span="12">{{ selectedSurveyorName || '系统自动分配' }}</el-descriptions-item>
              </el-descriptions>
            </el-card>

            <div class="flex justify-center gap-4">
              <el-button type="primary" @click="handleViewPolicy">查看我的保单</el-button>
              <el-button @click="resetForm">重新投保</el-button>
            </div>
          </template>
        </el-result>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import hxxp from '@/utils/hxxp';
import router from "@/router";

// 状态管理
const currentStep = ref(1);
const agreeTerms = ref(false);
const submitting = ref(false);
const submittedSuccessfully = ref(false);
const generatedPolicyId = ref('');
const loading = ref(false);

// 表单引用
const farmerForm = ref(null);
const insureForm = ref(null);

// 农户信息
const farmerInfo = ref({
  insuredId: '',    // 后端返回的农户唯一ID
  insuredName: '',  // 农户姓名
  phone: '',        // 手机号码
  idCard: '',       // 身份证号
  address: '',      // 详细地址
  bankName: '',     // 开户银行
  bankCard: ''      // 银行卡号
});

// 投保单信息
const insureOrder = ref({
  coverageType: '',          // 险种类型（1-种植业，2-养殖业，3-其他农险）
  coverageName: '',          // 险种名称（与后端insuranceCoverageName对应）
  insuranceSubject: '',      // 投保项目（对应后端insurance_subject字段）
  unitInsured: '0.00',       // 单位保额
  startDate: '',             // 保险起期
  endDate: '',               // 保险止期
  coverageArea: null,        // 承保面积（仅种植业）
  coverageQuantity: null,    // 承保数量（养殖业/其他）
  sumInsured: '0.00',        // 总保额
  totalPremium: '0.00',      // 总保费
  payStatus: 1,              // 缴费状态（1-待缴费）
  policyStatus: 1,           // 保单状态（1-待生效）
  insureUser: '',            // 投保业务员ID（与后端交互用）
  insuredId: ''              // 关联农户ID
});

// 新增：投保业务员相关状态
const surveyorOptions = ref([]); // 业务员下拉框选项（格式：[{id: '员工ID', name: '员工姓名'}, ...]）
const selectedSurveyor = ref(''); // 选中的业务员ID（与后端交互用）
const selectedSurveyorName = ref(''); // 选中的业务员姓名（页面展示用）

// 险种相关数据
const coverageNameList = ref([]); // 当前类型下的险种名称列表（后端接口返回）
const coverageTypeText = ref({    // 险种类型文本映射
  '1': '种植业',
  '2': '养殖业',
  '3': '其他农险'
});

// 计算属性
const minStartDate = computed(() => new Date());
const isCropType = computed(() => insureOrder.value.coverageType === '1');

// 面积/数量双向绑定
const currentQuantity = computed({
  get() {
    return isCropType.value ? insureOrder.value.coverageArea : insureOrder.value.coverageQuantity;
  },
  set(value) {
    if (isCropType.value) {
      insureOrder.value.coverageArea = value;
    } else {
      insureOrder.value.coverageQuantity = value;
    }
  }
});

// 表单验证规则
const farmerRules = ref({
  insuredName: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
  idCard: [
    {required: true, message: '请输入身份证号码', trigger: 'blur'},
    {pattern: /(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入18位有效身份证号', trigger: 'blur'}
  ],
  address: [
    {required: true, message: '请输入详细地址', trigger: 'blur'},
    {min: 5, message: '地址长度不能少于5个字符', trigger: 'blur'}
  ],
  bankName: [
    {required: true, message: '请选择开户银行', trigger: 'change'}
  ],
  bankCard: [
    {required: true, message: '请输入银行卡号', trigger: 'blur'},
    {min: 16, max: 19, message: '银行卡号长度在 16 到 19 位之间', trigger: 'blur'}
  ]
});

const insureRules = ref({
  coverageType: [
    {required: true, message: '请选择险种类型', trigger: 'change'}
  ],
  coverageName: [
    {required: true, message: '请选择险种名称', trigger: 'change'}
  ],
  insuranceSubject: [
    {required: true, message: '请输入投保项目', trigger: ['blur', 'change']},
    {min: 2, max: 32, message: '投保项目长度在 2 到 32 个字符之间', trigger: 'blur'}
  ],
  // 新增：投保业务员验证规则
  insureUser: [
    { required: true, message: '请选择投保业务员', trigger: ['change', 'blur'] }
  ],
  startDate: [
    {required: true, message: '请选择保险起期', trigger: ['change', 'blur']},
    {
      validator: (rule, value, callback) => {
        if (value && !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
          callback(new Error('保险起期格式错误，需为 yyyy-MM-dd（如 2025-09-18）'));
          return;
        }
        if (value) {
          const [year, month, day] = value.split('-').map(Number);
          const date = new Date(year, month - 1, day);
          if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
            callback(new Error('保险起期为无效日期，请重新选择'));
            return;
          }
        }
        callback();
      },
      trigger: ['change', 'blur']
    }
  ],
  endDate: [
    {required: true, message: '请选择保险止期', trigger: ['change', 'blur']},
    {
      validator: (rule, value, callback) => {
        if (value && !/^\d{4}-\d{2}-\d{2}$/.test(value)) {
          callback(new Error('保险止期格式错误，需为 yyyy-MM-dd（如 2025-12-31）'));
          return;
        }
        if (value) {
          const [year, month, day] = value.split('-').map(Number);
          const date = new Date(year, month - 1, day);
          if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
            callback(new Error('保险止期为无效日期，请重新选择'));
            return;
          }
        }
        if (value && insureOrder.value.startDate) {
          if (new Date(value) <= new Date(insureOrder.value.startDate)) {
            callback(new Error('保险止期必须晚于保险起期'));
            return;
          }
        }
        callback();
      }, trigger: ['change', 'blur']
    }
  ],
  coverageArea: [
    {required: () => isCropType.value, message: '请输入种植面积', trigger: 'blur'},
    {type: 'number', min: 0.1, message: '种植面积不能小于0.1亩', trigger: 'blur'}
  ],
  coverageQuantity: [
    {required: () => !isCropType.value, message: '请输入承保数量', trigger: 'blur'},
    {type: 'number', min: 1, message: '承保数量不能小于1', trigger: 'blur'}
  ],
  sumInsured: [
    {required: true, message: '总保额计算失败，请重新输入数量', trigger: 'change'},
    {type: 'number', min: 0.1, message: '总保额不能小于0.1元', trigger: 'change'}
  ]
});

// 页面初始化（新增业务员列表请求）
onMounted(() => {
  getSurveyorList(); // 页面加载时获取投保业务员列表
});

// 新增：获取投保业务员列表
const getSurveyorList = async () => {
  loading.value = true; // 显示加载状态
  try {
    const response = await hxxp.get('/aiStaffUser/worker', {
      params: {
        positionCode: 'PTN007' // 岗位编码：投保业务员专属编码
      }
    });
    if (response.code === 100200) {
      // 格式化选项：适配下拉框（若后端返回格式不同，需调整字段映射）
      surveyorOptions.value = response.data.map(staff => ({
        id: staff.id || staff.workNo, // 后端返回的业务员唯一标识
        name: staff.name || staff.realName // 业务员姓名（页面展示用）
      }));
      // 添加默认选项：系统自动分配
      surveyorOptions.value.unshift({
        id: 'system_auto',
        name: '系统自动分配'
      });

      // 设置默认选中项
      if (surveyorOptions.value.length > 0) {
        selectedSurveyor.value = 'system_auto';
        selectedSurveyorName.value = '系统自动分配';
        insureOrder.value.insureUser = 'system_auto';
      }
    } else {
      ElMessage.warning('获取投保业务员列表失败，将使用默认值');
      //  fallback：保留系统自动分配选项
      surveyorOptions.value = [{id: 'system_auto', name: '系统自动分配'}];
      selectedSurveyor.value = 'system_auto';
      selectedSurveyorName.value = '系统自动分配';
      insureOrder.value.insureUser = 'system_auto';
    }
  } catch (error) {
    console.error('获取投保业务员列表失败:', error);
    ElMessage.error('网络异常，获取投保业务员列表失败');
    //  fallback：保留系统自动分配选项
    surveyorOptions.value = [{id: 'system_auto', name: '系统自动分配'}];
    selectedSurveyor.value = 'system_auto';
    selectedSurveyorName.value = '系统自动分配';
    insureOrder.value.insureUser = 'system_auto';
  } finally {
    loading.value = false; // 关闭加载状态
  }
};

// 步骤切换
const nextStep = () => {
  if (currentStep.value === 1) {
    farmerForm.value.validate((validatePass, validateError) => {
      if (!validatePass) {
        console.error('农户表单验证失败', validateError);
        ElMessage.error('请完善必填字段并修正错误');
        return;
      }
      currentStep.value++;
      scrollToTop();
    });
  } else if (currentStep.value === 2) {
    insureForm.value.validate((validatePass, validateError) => {
      if (!validatePass) {
        console.error('投保详情验证失败', validateError);
        ElMessage.error('请完善必填字段并修正错误');
        return;
      }
      currentStep.value++;
      scrollToTop();
    });
  }
};

// 上一步
const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
    scrollToTop();
  }
};

/**
 * 险种类型变更
 */
const handleCoverageTypeChange = (typeCode) => {
  // 重置当前类型相关数据
  insureOrder.value.coverageType = typeCode;
  insureOrder.value.coverageName = '';
  insureOrder.value.insuranceSubject = '';
  insureOrder.value.unitInsured = '0.00';
  insureOrder.value.coverageArea = null;
  insureOrder.value.coverageQuantity = null;
  insureOrder.value.sumInsured = '0.00';
  insureOrder.value.totalPremium = '0.00';
  coverageNameList.value = [];

  // 调用后端接口
  loading.value = true;
  hxxp.get(`/coverage/names/${typeCode}`)
      .then(res => {
        loading.value = false;
        if (res.code === 100200 && Array.isArray(res.data)) {
          coverageNameList.value = res.data;
          if (coverageNameList.value.length === 0) {
            ElMessage.warning(`当前${coverageTypeText.value[typeCode]}暂无可用险种`);
          }
        } else {
          ElMessage.error('获取险种名称失败，请重新选择类型');
        }
      })
      .catch(error => {
        loading.value = false;
        console.error(`获取${coverageTypeText.value[typeCode]}险种列表失败`, error);
        ElMessage.error('网络异常，无法获取险种名称');
      });
};

/**
 * 选择险种名称后
 */
const handleCoverageNameSelect = (selectedName) => {
  if (!selectedName) {
    // 清空选择时重置数据
    insureOrder.value.insuranceSubject = '';
    insureOrder.value.unitInsured = '0.00';
    insureOrder.value.sumInsured = '0.00';
    return;
  }

  // 调用后端接口
  loading.value = true;
  const encodedName = encodeURIComponent(selectedName); // 中文参数编码
  hxxp.get(`/coverage/unitInsured/${encodedName}`)
      .then(res => {
        loading.value = false;
        if (res.code === 100200 && res.data !== null) {
          // 赋值单位保额（保留2位小数）
          insureOrder.value.unitInsured = Number(res.data).toFixed(2);
          // 若已输入数量，自动计算总保额
          if ((isCropType.value && insureOrder.value.coverageArea) || (!isCropType.value && insureOrder.value.coverageQuantity)) {
            handleQuantityInput();
          }
        } else {
          ElMessage.error('获取单位保额失败，请重新选择险种');
          insureOrder.value.unitInsured = '0.00';
          insureOrder.value.sumInsured = '0.00';
        }
      })
      .catch(error => {
        loading.value = false;
        console.error(`查询${selectedName}单位保额失败`, error);
        ElMessage.error('网络异常，无法获取单位保额');
        insureOrder.value.unitInsured = '0.00';
        insureOrder.value.sumInsured = '0.00';
      });
};

/**
 * 新增：投保业务员选择变更
 */
const handleSurveyorChange = (surveyorId) => {
  // 根据选中的业务员ID，找到对应的姓名
  const selectedItem = surveyorOptions.value.find(item => item.id === surveyorId);
  if (selectedItem) {
    selectedSurveyorName.value = selectedItem.name;
    insureOrder.value.insureUser = surveyorId; // 同步业务员ID到投保单（后端交互用）
  } else {
    selectedSurveyorName.value = '';
    insureOrder.value.insureUser = ''; // 清空选中状态
  }
};

/**
 * 面积/数量输入
 */
const handleQuantityInput = () => {
  const quantity = currentQuantity.value;
  const unitInsured = parseFloat(insureOrder.value.unitInsured);

  // 基础校验：数量和单位保额需有效
  if (isNaN(quantity) || quantity <= 0 || isNaN(unitInsured) || unitInsured <= 0) {
    insureOrder.value.sumInsured = '0.00';
    return;
  }

  // 计算总保额（保留2位小数，避免精度问题）
  const sumInsured = (unitInsured * quantity).toFixed(2);
  insureOrder.value.sumInsured = sumInsured;

  // 示例：前端计算保费（假设费率5%），可根据实际需求调整
  insureOrder.value.totalPremium = (parseFloat(sumInsured) * 0.05).toFixed(2);
};

/**
 * LocalDate格式校验函数
 */
const validateLocalDate = (dateKey) => {
  const dateValue = insureOrder.value[dateKey];
  const dateLabel = dateKey === 'startDate' ? '保险起期' : '保险止期';

  if (!dateValue) return true;

  // 格式校验
  if (!/^\d{4}-\d{2}-\d{2}$/.test(dateValue)) {
    ElMessage.warning(`${dateLabel}格式错误，需为 yyyy-MM-dd（如 2025-09-18）`);
    insureOrder.value[dateKey] = '';
    return false;
  }

  // 有效日期校验
  const [year, month, day] = dateValue.split('-').map(Number);
  const date = new Date(year, month - 1, day);
  if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
    ElMessage.warning(`${dateLabel}为无效日期（如 2025-02-30），请重新选择`);
    insureOrder.value[dateKey] = '';
    return false;
  }

  // 止期需晚于起期
  if (dateKey === 'endDate' && insureOrder.value.startDate) {
    if (new Date(dateValue) <= new Date(insureOrder.value.startDate)) {
      ElMessage.warning('保险止期必须晚于保险起期');
      insureOrder.value[dateKey] = '';
      return false;
    }
  }

  return true;
};

/**
 * 合并提交
 */
const submitAll = () => {
  if (!agreeTerms.value) {
    ElMessage.warning('请阅读并同意保险条款和隐私政策');
    return;
  }

  // 提交前校验：确保险种名称和投保项目不为空（双重保障）
  if (!insureOrder.value.coverageName) {
    ElMessage.error('请选择险种名称');
    return;
  }
  if (!insureOrder.value.insuranceSubject) {
    ElMessage.error('请输入投保项目');
    return;
  }

  // 校验是否选择了投保业务员
  if (!selectedSurveyor.value) {
    ElMessage.error('请选择投保业务员');
    return;
  }

  // 提交前校验日期格式
  if (!validateLocalDate('startDate') || !validateLocalDate('endDate')) {
    return;
  }

  submitting.value = true;
  try {
    // 先提交农户信息
    hxxp.post('/aiFarmerInsured/addOrUpdate', farmerInfo.value)
        .then(farmerRes => {
          if (farmerRes.code !== 100200) {
            throw new Error(farmerRes.msg || '农户信息提交失败');
          }
          console.log(farmerRes.data)
          const farmerData = farmerRes.data;
          farmerInfo.value.insuredId = farmerData;
          insureOrder.value.insuredId = farmerData;

          // 提交投保单信息
          const insureParams = {
            insuredId: insureOrder.value.insuredId,
            coverageType: insureOrder.value.coverageType,
            insuranceCoverageName: insureOrder.value.coverageName, // 险种名称
            insuranceSubject: insureOrder.value.insuranceSubject, // 投保项目
            unitInsured: insureOrder.value.unitInsured,
            startDate: insureOrder.value.startDate,
            endDate: insureOrder.value.endDate,
            coverageArea: insureOrder.value.coverageArea,
            coverageQuantity: insureOrder.value.coverageQuantity,
            sumInsured: insureOrder.value.sumInsured,
            totalPremium: insureOrder.value.totalPremium,
            payStatus: insureOrder.value.payStatus,
            policyStatus: insureOrder.value.policyStatus,
            insureUser: insureOrder.value.insureUser // 传递选中的业务员ID
          };
          console.log('提交的投保单参数：', insureParams);
          hxxp.post('/aiInsureOrder/add', insureParams)
              .then(insureRes => {
                submitting.value = false;
                if (insureRes.code === 100200) {
                  generatedPolicyId.value = insureRes.data.policyId;
                  submittedSuccessfully.value = true;
                  ElMessage.success('投保申请提交成功！');
                } else {
                  throw new Error(insureRes.msg || '投保单提交失败');
                }
              })
              .catch(insureError => {
                submitting.value = false;
                console.error('投保单提交失败', insureError);
                ElMessage.error(insureError.message || '投保单提交失败，请稍后重试');
              });
        })
        .catch(farmerError => {
          submitting.value = false;
          console.error('农户信息提交失败', farmerError);
          ElMessage.error(farmerError.message || '农户信息提交失败，请稍后重试');
        });
  } catch (error) {
    submitting.value = false;
    console.error('提交异常', error);
    ElMessage.error('系统异常，请联系管理员');
  }
};

/**
 * 辅助函数：获取数量输入框的标签
 */
const getQuantityLabel = () => {
  if (insureOrder.value.coverageType === '1') {
    return '种植面积（亩）';
  } else if (insureOrder.value.coverageType === '2') {
    if (insureOrder.value.coverageName && insureOrder.value.coverageName.includes('鸡')) {
      return '养殖数量（只）';
    } else {
      return '养殖数量（头）';
    }
  } else if (insureOrder.value.coverageType === '3') {
    if (insureOrder.value.coverageName) {
      if (insureOrder.value.coverageName.includes('大棚')) return '数量（座）';
      if (insureOrder.value.coverageName.includes('农机具')) return '数量（台）';
      return '数量（个）';
    }
    return '数量（个）';
  }
  return '数量';
};

/**
 * 辅助函数：获取数量单位
 */
const getQuantityUnit = () => {
  if (insureOrder.value.coverageType === '2') {
    return insureOrder.value.coverageName && insureOrder.value.coverageName.includes('鸡') ? '只' : '头';
  } else if (insureOrder.value.coverageType === '3') {
    if (insureOrder.value.coverageName) {
      if (insureOrder.value.coverageName.includes('大棚')) return '座';
      if (insureOrder.value.coverageName.includes('农机具')) return '台';
      return '个';
    }
    return '个';
  }
  return '头';
};

/**
 * 查看保单
 */
const handleViewPolicy = () => {
  window.location.href = `/insurance/policy-detail?policyId=${generatedPolicyId.value}`;
};

/**
 * 重置表单
 */
const resetForm = () => {
  currentStep.value = 1;
  submittedSuccessfully.value = false;
  agreeTerms.value = false;
  farmerInfo.value = {
    insuredId: '',
    insuredName: '',
    phone: '',
    idCard: '',
    address: '',
    bankName: '',
    bankCard: ''
  };
  insureOrder.value = {
    coverageType: '',
    coverageName: '',
    insuranceSubject: '',
    unitInsured: '0.00',
    startDate: '',
    endDate: '',
    coverageArea: null,
    coverageQuantity: null,
    sumInsured: '0.00',
    totalPremium: '0.00',
    payStatus: 1,
    policyStatus: 1,
    insureUser: '',
    insuredId: ''
  };
  // 重置业务员选择
  selectedSurveyor.value = 'system_auto';
  selectedSurveyorName.value = '系统自动分配';
  insureOrder.value.insureUser = 'system_auto';

  coverageNameList.value = [];
  scrollToTop();
};

/**
 * 滚动到顶部
 */
const scrollToTop = () => {
  window.scrollTo({top: 0, behavior: 'smooth'});
};

/**
 * 状态文本映射
 */
const getPayStatusText = (status) => {
  const statusMap = {1: '待缴费', 2: '缴费中', 3: '缴费成功', 4: '缴费失败'};
  return statusMap[status] || '未知状态';
};

const getPolicyStatusText = (status) => {
  const statusMap = {1: '待生效', 2: '已生效', 3: '已退保', 4: '已过期'};
  return statusMap[status] || '未知状态';
};

/**
 * 脱敏处理
 */
const maskIdCard = (idCard) => {
  if (!idCard) return '';
  return idCard.replace(/(\d{6})(\d{8})(\d{4})/, '$1********$3');
};

const maskBankCard = (bankCard) => {
  if (!bankCard) return '';
  return bankCard.replace(/(\d{4})(\d+)(\d{4})/, '$1 **** **** $3');
};
</script>

<style scoped>
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fadeIn {
  animation: fadeIn 0.3s ease-out forwards;
}

.insurance-application-submodule {
  background-color: #f5f7fa;
  min-height: calc(100vh - 20px);
}

.page-header {
  margin-bottom: 20px;
}

.step-content-container {
  transition: all 0.3s ease;
}

.form-actions {
  margin-top: 20px;
}

.el-form-item + .el-form-item {
  margin-top: 16px;
}

/* 步骤3确认按钮：险种名称为空时禁用 */
.el-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .step-content-container {
    padding: 15px;
  }

  .el-row {
    flex-direction: column;
  }

  .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
}
</style>
